<?php
Namespace Cyfy\Modules\BasicContent;

use \Cyfy\Modules\Users\Current;
use \Cyfy\Modules\Locale\Locale;
use \Cyfy\Modules\DibiPager\DibiPager;

class Module extends \Cyfy\Module
{
	static $hasRun = false;
	
    /**
     * Administration method.
     *
     * Available options are:
     * <ul>
     *     <li>addPage</li>
     *     <li>addBlock</li>
     *     <li>blocksList</li>
     *     <li>pagesList</li>
     * </ul>
     *
     * @param string Called method name.
     * @return mixed Callback result or FALSE.
     */
    static public function administration($name = "")
	{
        switch($name)
        {
            // ADD NEW PAGE
            case "addPage":
                return self :: addPage();

            // PAGES LIST
            case "pagesList":
                return self :: pagesList();
            
            // ADD NEW BLOCK
            case "addBlock":
                $form = new Forms\AddBlock();
                return $form -> show();
                
            // BLOCKS LIST
            case "blocksList":
                return self :: blocksList();
            
            // RETURN ARRAY
            case "":
                return array(
                    "addPage" => array("name" => self :: t(110) , "description" => self :: t(150), "permission"=> "add new"),
                    "pagesList" => array("name" => self :: t(120) , "description" => self :: t(180), "permission"=> "edit own"),
                    "addBlock" => array("name" => self :: t(130) , "description" => self :: t(160), "permission"=> "add new"),
                    "blocksList" => array("name" => self :: t(140) , "description" => self :: t(170), "permission"=> "edit own")
                );
                
            default:
                return false;
        }
	}
    
    /**
     * AJAX Callback;
     * @return mixed
     */
	static function ajax($name)
	{
		switch($name)
		{
			case "ajaxSave":
                $c = new Content('', $_POST["content"]);
                $c -> setBCID($_POST['bcid']);
				if($c -> save())
                {
                    \Cyfy\Message :: set(self :: t(330));
                }
                return;
                
            case "pagesList":
				return self :: ajaxPagesList();
            
            case "blocksList":
				return self :: ajaxBlocksList();
                
            case "deleteContent":
                return self :: ajaxDelete();
                
            case "get":
                if( $_POST["bcid"] != 0)
                {
                    $content = Content :: load($_POST["bcid"],$_POST["language"]);
                    if($content)
                        return $content -> get("h2");  
                }
                return false;
		}
        return false;
	}
    
    /**
     * Blocks
     * @param int BasicContent ID
     * return mixed
     */
    static function blocks($bcid = 0)
    {
        if($bcid != 0)
        {
            $content = Content :: load($bcid);
            
            if($content)
            {
                return $content -> get("h3");    
            }
            
            // not found in this language
            
            // if permissions, allow to create new
            if(\Cyfy\Cyfy ::  permission("BasicContent", "add new"))
            {
                $all = \Cyfy\Language :: getAll();
                return "<input type=\"submit\" onclick=\"Cyfy.redirectTo('administration/BasicContent/blocksList/" . $bcid . "?language=" . \Cyfy\Language :: getActive() . "')\" value=\"" . self :: t(321, array($all[\Cyfy\Language :: getActive()])) . "\" />";
            }
            
            // if not, return empty
            return "";
        }
        
        $result = \dibi :: query("SELECT [bcid], [title] FROM [:cyfy:BasicContent] WHERE [language] = %s ORDER BY [title] ASC", \Cyfy\Language :: getActive());
        
        // nothing found
        if(count($result)==0)
        {
            return false;
        }
        
        // return list
        return $result -> fetchPairs('bcid', 'title');
    }
	
    static public function get($bcid)
    {
        $content = Content :: load($bcid);
        // found
		if($content)
        {
            return $content -> getPage();
        }

        // if not found, look in other languages
            
        // if translations not enabled
        if(!\Cyfy\Modules :: isEnabled("Translations"))
        {
            return false;                
        }   
        
        // try load all languages
        $result = \dibi :: query("SELECT [bcid], [title], [language] FROM [:cyfy:BasicContent] WHERE [bcid] = '$bcid'");
        
        // if not found, ERROR. In fact, no user should get this message.
        if(count($result) == 0)
        {
            // not found
            return "NOT FOUND";
        }
        
        $all = \Cyfy\Language :: getAll();
        $language = \Cyfy\Language :: getActive();
        
        // show options for loading
        $output = \Cyfy\Message :: get(self::t(310),\Cyfy\Message::ERROR);
        $output .= "<ul class=\"bcNotFound\">";
        foreach($result as $bc)
        {
            $output .= "<li><input onclick=\"Cyfy.ajax('BasicContent', 'get', '#basicContentHelper-{$unique}', 'bcid={$bcid}&language={$bc["language"]}')\" type=\"submit\" value=\"" . self :: t(311, array($all[$bc["language"]])) . "\" /></li>";
        }
        
        // if permissions, allow to create new
        if(\Cyfy\Cyfy ::  permission("BasicContent", "add new") && \Cyfy\Cyfy :: permission("BasicContent", "edit own"))
        {
            $output .= "<li><input type=\"submit\" onclick=\"Cyfy.redirectTo('administration/BasicContent/pagesList/" . $bcid . "?language=" . $language . "')\" value=\"" . self :: t(321, array($all[$language])) . "\" /></li>";
        }
        
        $output .= "</ul>";
        return "<div id=\"basicContentHelper-{$unique}\">" . $output . "</div>";        
    }
    

  
	
    /**
     * Adding page
     * @return string HTML content 
     */
    static private function addPage()
    {
    	// menus
        $menuList = \Cyfy\Modules\Menu\Menu :: getAll();
        
        // add 'do not add to menu'
		$menuList[0] = self :: t(260);
        
		// form
		$form = new Forms\AddPage();
        
        // fills select with menus and sets active value to dont add
		$form -> fillSelect("menu", $menuList);
        $form -> setData(array('menu'=>0));
		return $form -> show();
	}
    
    /**
     * Editing page
     * @return string HTML content 
     */
    static private function editPage($bcid)
	{
		$result = \dibi :: query("SELECT * FROM [:cyfy:BasicContent] WHERE [bcid] = %i", $bcid);
		
		// if not found
		if(count($result) == 0)
        {
			\Cyfy\Message :: set(self :: t(410), \Cyfy\Message::ERROR);
			return "";
		}
       
       $output = "<h2>" . self :: t(710) . "</h2>";
       
        // fetch path ----- is it neccessary??? TODO
		$resultPath = \dibi :: query("SELECT [fid], [path] FROM [:cyfy:Cyfy-filesystem] WHERE [module] = 'BasicContent' AND id = '{$bcid}' LIMIT 1");
		if(count($resultPath))
		{
			$path = $resultPath -> fetch();
		}
        else
        {
			$path = array("fid"=>0, "path"=>"");
		}
		
		// menus
		$menuList = \Cyfy\Modules\Menu\Menu :: getAll();
        
        // clean path
        $cleanPath = strtr($path["path"], array("\/"=> "/"));
        // is the page in a menu??
        $inMenu = array();
        $resultMenu = \dibi :: query("SELECT [mid] FROM [:cyfy:Menu-items] WHERE [link] = %s", $cleanPath, " AND [language] = %s", \Cyfy\Language :: getActive());
        if(count($resultMenu) != 0){
            foreach($resultMenu as $mi)
            {
                $inMenu[] = $mi["mid"];
            }
        }
        
        // fetch $results
        $contents = $result -> fetchAssoc('language');
        
        
        // form
        $form = new Forms\EditPage(true);
        
        // fill contents
        $form -> bcData = $contents;
        
        // build structure
        $form -> structure();
        
        $form -> fillSelect("menu", $menuList);

    
        $data = array("menu" => $inMenu, "path" => $cleanPath, "oldPath" => $cleanPath, "bcid" => $bcid);
        $form -> setData($data);
        $output .= $form -> show();

        
		return $output;
	}
    
    
    /**
     * Editing page
     * @return string HTML content 
     */
    static private function editBlock($bcid)
	{
		$result = \dibi :: query("SELECT * FROM [:cyfy:BasicContent] WHERE [bcid] = %i", $bcid);
		
		// if not found
		if(count($result) == 0)
        {
			\Cyfy\Message :: set(self :: t(410), \Cyfy\Message::ERROR);
			return "";
		}
        
        $output = "<h2>" . self :: t(720) . "</h2>";
     
         // fetch $results
        $contents = $result -> fetchAssoc('language');
        
        // form
        $form = new Forms\EditBlock(true);
        
        // fill contents
        $form -> bcData = $contents;
        
        // build structure
        $form -> structure();
        
		
			
        $data = array("bcid" => $bcid);
        $form -> setData($data);

        $output .= $form -> show();

		return $output;
	}
    
    /**
     * Pages list
     */
    static private function pagesList()
    {
        $id = \Cyfy\Cyfy ::  arg(3);
        // if edit
        if(is_numeric($id))
        {
            return self :: editPage($id);
        }
        
        //pager
        $pager = new DibiPager('adminPagesList');
        $pager -> ajaxCall('BasicContent', 'pagesList', '#adminPagesList');
        $pager -> sortForm = new \Cyfy\Modules\DibiPager\Forms\SortBy(true);
        $pager -> sortForm -> options = array(
            '[:cyfy:BasicContent].[title]' => self :: t(510),
            '[:cyfy:Cyfy-filesystem].[path]' => self :: t(520),
            '[:cyfy:BasicContent].[updated], [:cyfy:BasicContent].[created]' => self :: t(530),
            '[:cyfy:BasicContent].[language]' => self :: t(540),
        );
                
        // show form
        $output = $pager -> showSortForm();
        
        // show list
        $output .= "<br /><div id=\"adminPagesList\">" . self :: ajaxPagesList() . "</div>";
        $output .= $pager -> pager('SELECT count(*) FROM [:cyfy:Cyfy-filesystem] WHERE [module] = \'BasicContent\'');
        return $output;
    }
    
    /**
     * Returns list of pages
     */
    static private function ajaxPagesList()
    {
        if(!(\Cyfy\Cyfy ::  permission('BasicContent', 'edit own') || \Cyfy\Cyfy ::  permission('BasicContent', 'edit all')))
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
       
        // select query 
        $query = array(
            'SELECT [:cyfy:BasicContent].[bcid], [:cyfy:BasicContent].[title], [:cyfy:BasicContent].[creator], [:cyfy:Cyfy-filesystem].[path], [:cyfy:BasicContent].[created], [:cyfy:BasicContent].[language], [:cyfy:BasicContent].[updated], [:cyfy:BasicContent].[language]',
            'FROM [:cyfy:Cyfy-filesystem]',
            'LEFT JOIN [:cyfy:BasicContent] ON ([:cyfy:Cyfy-filesystem].[module] = \'BasicContent\' AND [:cyfy:BasicContent].[bcid] = [:cyfy:Cyfy-filesystem].[id])',
            'WHERE [:cyfy:BasicContent].[title] != ""'
        );
        
        // if not multi
        if(!\Cyfy\Language :: isMulti())
        {
            $query[] = " AND [:cyfy:BasicContent].[language] = %s";
            $query[] = \Cyfy\Language :: getActive();
        }
        
        // pager
        $pager = new DibiPager('adminPagesList');
        $pager -> ajaxCall('BasicContent', 'pagesList', '#adminPagesList');
        $result = $pager -> query($query);
        
        // if no pages
		if (count($result) == 0) 
		{
			return \Cyfy\Message :: get(self :: t(610), \Cyfy\Message::WARNING);
		}
    
        // header
        $header = array(self :: t(20), self :: t(30), self :: t(50),self :: t(60));
        if(\Cyfy\Language :: isMulti()){
            array_unshift($header, "");
        }
        
		// creating table
		$table = new \Cyfy\Modules\Objects\Table();
		$table -> header($header);

        
		foreach ($result as $bc) 
		{
            $bc = (array) $bc;
            
            $path = strtr($bc["path"], array("\/"=> "/"));
		
            $bc["path"] = "<a href=\"" . \Cyfy\Cyfy ::  getPath($path) . "\">" . $path . "</a>";
            
            $time = ($bc["updated"] != '0000-00-00 00:00:00') ? $bc["updated"] : $bc["created"];
            
            // EDIT
            $buttons = '';
            if(($bc["creator"] == Current :: $uid && Current :: hasPermission("BasicContent", "edit own") ) || Current :: hasPermission("BasicContent", "edit all"))
            {
                $buttons = "<a class=\"button\" href=\"" . \Cyfy\Cyfy :: getPath("administration/BasicContent/pagesList/" . $bc["bcid"]) . "?language={$bc['language']}\">E</a> ";
            }

            // DELETE
            if(($bc["creator"] == Current :: $uid && Current :: hasPermission("BasicContent", "delete own") ) || Current :: hasPermission("BasicContent", "delete all"))
            {
               $buttons .= "<a class=\"button button-warning\" onclick=\"if(confirm('" . self :: t(621,array($bc['title'])) . "')){  Cyfy.ajax('BasicContent', 'deleteContent', '', 'bcid={$bc['bcid']}&language={$bc['language']}', 'Cyfy.ajax(\'BasicContent\', \'pagesList\', \'#adminPagesList\');') };\" href=\"#\">X</a> ";
            }
            
            // flag
            $fl = "";
            if(\Cyfy\Modules :: isEnabled('Translations'))
            {
                $fl = \Cyfy\Modules\Translations\Module :: getFlag($bc["language"]); 
            }
            // ROW
            $row = array($bc["title"], $bc["path"], Locale :: getTime($time),$buttons);
            
            // if multi, add flag
            if(\Cyfy\Language :: isMulti())
            {
                array_unshift($row, \Cyfy\Modules\Translations\Module :: getFlag($bc["language"]));
            }
            
            // adding row
			$table -> row($row);
		}
		return $table -> show();
    }
    
    /**
     * Blocks list
     */
    static private function blocksList()
    {
        $id = \Cyfy\Cyfy ::  arg(3);
        if(is_numeric($id))
        {
            return self :: editBlock($id);
        }
        $pager = new DibiPager('adminBlocksList');
        $pager -> ajaxCall('BasicContent', 'blocksList', '#adminBlocksList');
        $output = "<div id=\"adminBlocksList\">" . self :: ajaxBlocksList() . "</div>";
        $output .= $pager -> pager('SELECT count(*) FROM [:cyfy:BasicContent] WHERE bcid NOT IN(SELECT [id] FROM [:cyfy:Cyfy-filesystem] WHERE [module] = "BasicContent")');

        return $output;
    }
               
     /**
     * Returns list of pages
     */
    static private function ajaxBlocksList()
    {
        if(!(\Cyfy\Cyfy ::  permission('BasicContent', 'edit own') || \Cyfy\Cyfy ::  permission('BasicContent', 'edit all')))
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
    
        $query = array('SELECT * FROM [:cyfy:BasicContent] WHERE [bcid] NOT IN(SELECT [id] FROM [:cyfy:Cyfy-filesystem] WHERE [module] = "BasicContent")');
        
        // if not multi, show just for default language
        if(!\Cyfy\Language :: isMulti())
        {
            $query[] = " AND [:cyfy:BasicContent].[language] = %s";
            $query[] = \Cyfy\Language :: getActive();
        }
        
        // ordering
        $query[] = 'ORDER BY [bcid], [language] ASC';      
        
        
        $pager = new DibiPager('adminBlocksList');
        $pager -> ajaxCall('BasicContent', 'blocksList', '#adminBlocksList');
        $result = $pager -> query($query);
        
        // if no blocks
		if (count($result) == 0) 
		{
			return \Cyfy\Message :: get(self :: t(610), \Cyfy\Message::WARNING);
		}
    
        // header
        $header = array(self :: t(20), self :: t(50), self :: t(60));
        if(\Cyfy\Language :: isMulti()){
            array_unshift($header, "");
        }
		// creating table
		$table = new \Cyfy\Modules\Objects\Table();
		$table -> header($header);
				
		foreach ($result as $bc) 
		{
            $bc = (array) $bc;
            $time = ($bc["updated"] != '0000-00-00 00:00:00') ? $bc["updated"] : $bc["created"];
            
            $buttons = '';
            // EDIT
            if(($bc["creator"] == Current :: $uid && Current :: hasPermission("BasicContent", "edit own") ) || Current :: hasPermission("BasicContent", "edit all"))
            {
                $buttons = "<a class=\"button\" href=\"" . \Cyfy\Cyfy :: getPath("administration/BasicContent/blocksList/" . $bc["bcid"]) . "?language={$bc['language']}\">E</a> ";
            }

            // DELETE
            if(($bc["creator"] == Current :: $uid && Current :: hasPermission("BasicContent", "delete own") ) || Current :: hasPermission("BasicContent", "delete all"))
            {
               $buttons .= "<a class=\"button button-warning\" onclick=\"if(confirm('" . self :: t(621, array($bc['title'])) . "')){  Cyfy.ajax('BasicContent', 'deleteContent', '', 'bcid={$bc['bcid']}&language={$bc['language']}', 'Cyfy.ajax(\'BasicContent\', \'blocksList\', \'#adminBlocksList\');') }; return false;\" href=\"#\">X</a> ";
            }
            
            // ROW
            $row = array($bc["title"], Locale :: getTime($time), $buttons);
            
            // if multi, add flag
            if(\Cyfy\Language :: isMulti())
            {
                array_unshift($row, \Cyfy\Modules\Translations\Module :: getFlag($bc["language"]));
            }
            
            // adding row
			$table -> row($row);
		}
		return $table -> show();
    }
    
    /**
     * Deletes content from ajax call.
     */
    static private function ajaxDelete()
    {
        // fetch path
		$resultPath = \dibi :: query("SELECT [path] FROM [:cyfy:Cyfy-filesystem] WHERE [module] = 'BasicContent' AND [id] = %i LIMIT 1", $_POST['bcid']);
		if(count($resultPath))
        {
			$path = strtr($resultPath -> fetchSingle(), array("\/"=> "/"));
		}
        else
        {
			$path = "";
		}
        
        // load
        $content = Content :: load($_POST['bcid'], $_POST['language']);
        if(!$content) return false;
        
        // try to delete
        if(!$content -> delete())
        {
            return false;
        }
        
        // page deleted
        \Cyfy\Message :: set(self :: t(631, array($content -> getTitle())));
        
        // if no other contents with this id, remove FS, BLOCKS and MENUS
        $other = \dibi :: query('SELECT count(*) FROM [:cyfy:BasicContent] WHERE [bcid] = %i ', $_POST['bcid']) -> fetchSingle();
        if($other != 0)
        {
            return true;
        }
        
        // if no other
        if($path != '')
        {
            // delete MENU
            \Cyfy\Modules\Menu\Menu :: removeItemByLink($path);
            
            // delete FS
            \Cyfy\Cyfy ::  unregisterPathByModule('BasicContent', $_POST['bcid']);
        }
        
        // delete blocks
        \Cyfy\Blocks :: updateBlock('BasicContent', $_POST['bcid']);
    }
}

